package com.lengxf.netty.controller;

import cn.hutool.json.JSONUtil;
import com.lengxf.netty.config.ChannelContextHolder;
import com.lengxf.netty.param.CommandEnum;
import com.lengxf.netty.param.HeartBeatReqParam;
import com.lengxf.netty.param.RegisterReqParam;
import com.lengxf.netty.param.ReqMessage;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jakarta.annotation.PostConstruct;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Lengxf
 * @version 1.0.0
 * @ClassName TestController.java
 * @Description 吃
 * @createTime 2022-10-10日 11:41:00
 */
@RestController
@RequestMapping
public class TestController {

    private final AtomicInteger atomicInteger = new AtomicInteger();

    @Order(2)
    @GetMapping("test")
    public String test() {
        ReqMessage nettyMessage = new ReqMessage();
        nettyMessage.setCommand(CommandEnum.REGISTER);
        RegisterReqParam regis = new RegisterReqParam();
        regis.setWcName("BSL010R01");
        nettyMessage.setData(regis);
        Channel channel = ChannelContextHolder.getChannel();
        if (channel != null) {
            channel.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(nettyMessage)));
        }
        return "success";
    }

    @PostConstruct
    public void testJob() {
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                heartReq();
            }
        }).start();
    }

    private void heartReq() {
        ReqMessage nettyMessage = new ReqMessage();
        nettyMessage.setCommand(CommandEnum.HEART_BEAT);
        HeartBeatReqParam beatReqParam = new HeartBeatReqParam();
        beatReqParam.setWcName("BSL010R01");
        nettyMessage.setData(beatReqParam);
        Channel channel = ChannelContextHolder.getChannel();
        if (channel != null) {
            channel.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(nettyMessage)));
        }
    }


}
